package com.ytt.myspringboot_project.o1kafka;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.Random;

@Component
public class O1TemperatureProducer {

    @Value("${kafka.topic.temperature}")
    private String topic;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    private Random random = new Random();
    private DecimalFormat df = new DecimalFormat("#.##");

    // 每5秒发送一次温度数据
    public void sendTemperatureData() {
        // 模拟温度数据 (15.0 - 35.0之间)
        double temperature = 15 + (35 - 15) * random.nextDouble();
        String message = "时间: " + LocalDateTime.now() + ", 温度: " + df.format(temperature) + "°C";

        kafkaTemplate.send(topic, message);
        System.out.println("生产者发送消息: " + message);
    }
}
